const { logHelper } = require("../../helper");
var logUtils = require("../log/logUtils");
var ocrCharMap = require("./ocrCharMap");

// var cpuThreadNum = 4;
// // PaddleOCR 移动端提供了两种模型：ocr_v3_for_cpu与ocr_v3_for_cpu(slim)，此选项用于选择加载的模型,默认true使用v3的slim版(速度更快)，false使用v3的普通版(准确率更高）
// var useSlim = true;
// // 是否使用v4版本
// var useV4 = false;

// $ocr.initWithModel({ useV4 });
module.exports = {
  hasInit: false,
  captureImg: null,
  init() {
    if (this.hasInit) {
      return;
    } else {
      shizuku("appops set org.autojs.autojs6 PROJECT_MEDIA allow");
      this.hasInit = true;
      setTimeout(() => {
        if (!requestScreenCapture()) {
          toastLog("请求截图权限失败");
          exit();
        }
      }, 1000);
    }
  },
  updateCaptureImg() {
    var startTime = Date.now();
    var showing = logUtils.showing;
    if (showing) {
      logUtils.hide();
      sleep(0.1 * 1000);
    }
    this.captureImg = captureScreen();
    setTimeout(() => {
      this.captureImg && this.captureImg.recycle();
    }, 1000);
    if (showing) {
      logUtils.show();
    }
    if (!this.captureImg) {
      toastLog("截图失败");
    }
    var endTime = Date.now();
    var hasExec = (endTime - startTime) / 1000;
    if (hasExec > 1) {
      logUtils.log("GCI: 截图耗费-" + hasExec + "-s");
    }
  },
  getOcrResults() {
    console.log("开始识别");
    // var ocrResults = ocr.paddle.detect(this.captureImg, {
    var ocrResults = ocr.mlkit.detect(this.captureImg, {
      useSlim: false,
      cpuThreadNum: 4,
    });
    if (Array.isArray(ocrResults)) {
      return ocrResults.map((item) => {
        var obj = {};
        obj.text = item.label;
        obj.bounds = item.bounds;
        obj.confidence = item.confidence;
        return obj;
      });
    }
    return ocrResults;
  },

  getRegExpConfig(content) {
    var regExpStr = content
      .split("")
      .map(function (item) {
        var match = ocrCharMap[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    return {
      text: content,
      regExp: new RegExp(regExpStr, "gi"),
    };
  },
  getLogText() {
    var ocrResults = this.getOcrResults();
    if (Array.isArray(ocrResults)) {
      return ocrResults
        .map((item, index) => index + ":" + item.text)
        .join("\n");
    } else {
      return "ocr识别失败";
    }
  },
  getRegExpStartWith(content) {
    var regExpStr = content
      .split("")
      .map(function (item) {
        var match = ocrCharMap[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    return {
      text: content,
      regExp: new RegExp("^" + regExpStr + "$", "gi"),
    };
  },
  getRegExp(regText) {
    return new RegExp(regText, "gi");
  },

  getBaseRegText(content) {
    return content
      .split("")
      .map(function (item) {
        var match = ocrCharMap[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
  },
  contain(content) {
    var baseRegText = this.getBaseRegText(content);
    var regExp = this.getRegExp(baseRegText);
    const ocrResults = this.getOcrResults();
    const length = ocrResults.length;
    for (var index = 0; index < length; index++) {
      var ocrResult = ocrResults[index];
      if (regExp.test(ocrResult.text)) {
        return ocrResult;
      }
    }
    this.logocrtext(content, ocrResults);
    return false;
  },

  startWith(content) {
    const regExp = this.getRegExpStartWith(content);
    const ocrResults = this.getOcrResults();
    const length = ocrResults.length;
    for (var index = 0; index < length; index++) {
      var ocrResult = ocrResults[index];
      if (regExp.regExp.test(ocrResult.text)) {
        return ocrResult;
      }
    }
    logHelper.log("ocrUtils.startWith 没找到:" + content);
    this.logocrtext(content, ocrResults);
    return false;
  },

  logocrtext(content, ocrResults) {
    const ocrTexts = ocrResults
      .map((item, index) => {
        return `${index}:${item.text}`;
      })
      .join("&&&");
    logHelper.log(`ocrUtils.logocrtext 没找到${content}${ocrTexts}`);
  },

  captureAndLog() {
    var ocrResults = this.getOcrResults();
    this.logOcrResults(ocrResults);
  },
  logOcrResults(ocrResults) {
    logUtils.log(typeof ocrResults);
    if (Array.isArray(ocrResults)) {
      console.show();
      logUtils.log(
        "LOR1:",
        "\n",
        ocrResults.map((item) => item.text).join(",")
      );
    } else {
      console.show();
      logUtils.log("LOR2:", "\n", JSON.stringify(ocrResults)); // TODO: 待确认是否需要do
    }
  },
  ocrResultsExist(ocrResults, regExpConfig) {
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      if (regExpConfig.regExp.test(ocrResult.text)) {
        return ocrResult;
      }
    }
    return false;
  },
  regExpConfigExist(ocrResults, regExpConfigs) {
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      for (var index2 = 0; index2 < regExpConfigs.length; index2++) {
        var regExpConfig = regExpConfigs[index2];
        if (regExpConfig.regExp.test(ocrResult.text)) {
          return ocrResult;
        }
      }
    }
    return false;
  },
  regExpConfigExistSome(ocrResults, regExpConfigs) {
    var results = [];
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      for (var index2 = 0; index2 < regExpConfigs.length; index2++) {
        var regExpConfig = regExpConfigs[index2];
        if (regExpConfig.regExp.test(ocrResult.text)) {
          results.push(ocrResult);
        }
      }
    }
    return results;
  },
  captureExistsText(content, logOcrResults, ignoreLog) {
    var regExpConfig = this.getRegExpConfig(content);
    var ocrResults = this.getOcrResults();
    var ocrResult = this.ocrResultsExist(ocrResults, regExpConfig);
    if (ocrResult) {
      if (!ignoreLog) {
        logUtils.log("CET:", "找到", regExpConfig.text, "/", ocrResult.text);
      }
      return ocrResult;
    } else {
      if (logOcrResults) {
        this.logOcrResults(ocrResults);
      }
      return false;
    }
  },
  captureExistsOneText(contents, logOcrResults, ignoreLog) {
    if (!Array.isArray(contents)) {
      contents = [contents];
    }
    var ocrResults = this.getOcrResults();
    var regExpConfigs = contents.map((content) =>
      this.getRegExpConfig(content)
    );
    var ocrResult = this.regExpConfigExist(ocrResults, regExpConfigs);
    if (ocrResult) {
      if (!ignoreLog) {
        logUtils.log("CEOT:", "找到", contents.join(","), "/", ocrResult.text);
      }
      return ocrResult;
    } else {
      logUtils.log("CEOT:", "没找到", contents.join(","));
      if (logOcrResults) {
        this.logOcrResults(ocrResults);
      }
      return false;
    }
  },
  captureExistsSomeText(contents, logOcrResults, ignoreLog) {
    if (!Array.isArray(contents)) {
      contents = [contents];
    }
    var ocrResults = this.getOcrResults();
    var regExpConfigs = contents.map((content) =>
      this.getRegExpConfig(content)
    );
    var results = this.regExpConfigExistSome(ocrResults, regExpConfigs);
    if (results.length > 0) {
      if (!ignoreLog) {
        logUtils.log(
          "CEOT:",
          "找到",
          contents.join(","),
          "/",
          results.map((item) => item.text).join(",")
        );
      }
      return results;
    } else {
      logUtils.log("CEOT:", "没找到", contents.join(","));
      if (logOcrResults) {
        this.logOcrResults(ocrResults);
      }
      return false;
    }
  },

  captureExistsAllText(contents, logOcrResults, ignoreLog) {
    if (!Array.isArray(contents)) {
      contents = [contents];
    }
    var ocrResults = this.getOcrResults();
    var regExpConfigs = contents.map((content) =>
      this.getRegExpConfig(content)
    );
    var findResults = [];
    for (var index = 0; index < regExpConfigs.length; index++) {
      var regExpConfig = regExpConfigs[index];
      var ocrResult = this.ocrResultsExist(ocrResults, regExpConfig);
      if (ocrResult) {
        findResults.push(ocrResult);
      }
    }
    if (findResults.length == contents.length) {
      if (!ignoreLog) {
        logUtils.log(
          "CEAT:",
          "找到",
          "\n",
          contents.join(","),
          "\n",
          findResults.map((item) => item.text).join(",")
        );
      }
      return true;
    } else {
      logUtils.log("CEAT:", "没找到", contents.join(","));
      if (logOcrResults) {
        this.logOcrResults(ocrResults);
      }
      return false;
    }
  },
};
